package com.ruoyi.web.controller.product;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.shop.ai.service.IAiService;
import com.ruoyi.shop.common.utils.IPUtils;
import com.ruoyi.shop.modules.domain.Comment;
import com.ruoyi.shop.modules.service.ICommentService;
import com.ruoyi.shop.modules.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品评价Controller
 *
 * @author zjc
 * @date 2024-07-02
 */
@RestController
@RequestMapping("/product/comment")
public class CommentController extends BaseController
{
    @Autowired
    private ICommentService commentService;
    @Autowired
    private IAiService aiService;
    @Autowired
    private IProductService productService;

    /**
     * 查询商品评价列表
     */
    @PreAuthorize("@ss.hasPermi('product:comment:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam Long id)
    {
        startPage();
        List<Comment> list = commentService.selectCommentListByProductId(id);
        return getDataTable(list);
    }


    /**
     * 新增商品评价
     */
    @Log(title = "商品评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Comment comment) {
        // 获取登录用户信息
        LoginUser loginUser = getLoginUser();
        if (loginUser == null) {
            return AjaxResult.error("用户未登录或登录信息已过期");
        }

        // 获取并设置评论相关信息
        String ipaddr = loginUser.getIpaddr();
        // 根据ip获取城市信息
        String city = IPUtils.getCityByIP(ipaddr);
        // 设置评论信息
        comment.setIpCity(city);
        comment.setProductAttribute(loginUser.getLoginLocation());
        comment.setMemberIp(ipaddr);
        comment.setMemberNickName(loginUser.getUsername());

        // AI获取评论内容的摘要
        String content = comment.getContent();
        if (content != null && !content.isEmpty()) {
            List<String> commentAbstract = aiService.getAiResult(content);
            // 处理摘要
            if (commentAbstract != null && !commentAbstract.isEmpty()) {
                // 将摘要列表转换为字符串，并以逗号分隔
                String keywords = String.join(",", commentAbstract);
                // 根据业务需求处理关键词
                productService.updateKeywordsById(comment.getProductId(), keywords); // 更新商品关键词
            }
        }

        // 插入评论，并返回结果
        return toAjax(commentService.insertComment(comment));
    }


}




